<?php
/**
 * Created by PhpStorm.
 * User: BlueIdeaLirui
 * Date: 2019/09/04
 * Time: 14:58
 */

namespace business\elasticsearch\services;

use business\search\models\SearchHotModel;
use business\search\models\SearchRecordModel;
use common\utils\DateTimeUtils;

class SearchLogsService
{
    /**
     * 保存搜索记录
     * @param $keyword
     * @param $analysisKeyword
     * @param $resultRows
     * @param $searchModule
     * @param $source
     */
    public function addSearchRecord($keyword, $analysisKeyword, $resultRows, $searchModule, $source)
    {
        if (empty($keyword)) {
            return;
        }
        $searchRecord = new SearchRecordModel();
        $searchRecord->userId = '';
        $searchRecord->userType = '';
        $searchRecord->keyword = $keyword;
        $searchRecord->analysisKeyword = $analysisKeyword;
        $searchRecord->resultRows = $resultRows;
        $searchRecord->searchModule = $searchModule;
        $searchRecord->source = $source;
        //$searchRecord->ipAddress = IpAddressUtil::getClientIPAddress();
        $searchRecord->searchDate = DateTimeUtils::date();
        $searchRecord->save();
        // 当搜索结果不存在 ，不记录热门搜索
        if (empty($resultRows)) {
            return;
        }
        /** @var SearchHotModel $searchResult */
        $searchResult = SearchHotModel::find()->where(["searchModule" => $searchModule, "keyword" => $keyword])->one();
        if (empty($searchResult)) {
            $searchHot = new SearchHotModel();
            $searchHot->searchModule = $searchModule;
            $searchHot->keyword = $keyword;
            $searchHot->count = 1;
            $searchHot->save();
        } else {
            $searchResult->count = intval($searchResult->count) + 1;
            $searchResult->update();
        }
    }
}
